from django.shortcuts import render, redirect

from app01 import models
from app01.utils.pagination import Pagination
from app01.utils.form import PrettynumModelForm


def prettynum_show(request):
    data_dict = {}
    search_data = request.GET.get('q', '')
    if search_data:
        data_dict['mobile__contains'] = search_data

    queryset = models.PrettyNum.objects.filter(**data_dict).order_by('-level')

    page_object = Pagination(request, queryset)

    context = {
        'search_data': search_data,
        'queryset': page_object.page_queryset,  # 分完页的数据
        'page_str': page_object.html()  # 页码
    }
    return render(request, 'prettynum_show.html', context)


def prettynum_add(request):
    # 添加靓号
    if request.method == 'GET':
        form_obj = PrettynumModelForm()
        return render(request, 'prettynum_add.html', {'form_obj': form_obj})

    form_obj = PrettynumModelForm(request.POST)
    if form_obj.is_valid():
        form_obj.save()
        return redirect('/prettynum/show/')

    return render(request, 'prettynum_add.html', {'form_obj': form_obj})